package crazyFace.system.app;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
 
public class Sprite {
	// direction = 0 up, 1 left, 2 down, 3 right,
	// animation = 3 back, 1 left, 0 front, 2 right
	int[] DIRECTION_TO_ANIMATION_MAP = { 3, 1, 0, 2 };
	protected int rows = 4;
	protected int columns = 3;
	protected GameView gameView;
	protected Bitmap bmp;
	protected float x = 0;
	protected float y = 0;
	protected float xSpeed;
	protected float ySpeed;
	protected int currentFrame = 0;
	protected boolean aniForward;
	public int aniRow = 0;
	protected int width;
	protected int height;
	protected int dstwidth;
	protected int dstheight;
	protected boolean living = true;
	
	
	public Sprite(GameView gameView, Bitmap bmp, int rows, int columns) {
		this.rows = rows;
		this.columns = columns;
		this.width = bmp.getWidth() / columns;
		this.height = bmp.getHeight() / rows;
		this.dstwidth = this.width;
		this.dstheight = this.height;
		this.gameView = gameView;
		this.bmp = bmp;
		
	}	
 
	protected void update() {
		
	}
       
	public void updateFrameSimple(){
		aniRow = 0;
    	   
		if(currentFrame > columns - 2){
			aniForward = false;
		}else if(currentFrame < 1){
			aniForward = true;
		}
		
		if(aniForward){
			++currentFrame;
		}else if(!aniForward){
			--currentFrame;
		}
	}
       
	public void updateFrameRows(){
		aniRow = getAnimationRow();
		
		if(currentFrame > columns - 2){
			aniForward = false;
		}else if(currentFrame < 1){
			aniForward = true;
		}
    	   
		if(aniForward){
			if(xSpeed != 0 || ySpeed != 0){
				++currentFrame;
			}
		}else{
			if(xSpeed != 0 || ySpeed != 0){
				--currentFrame;
			}
		}
	}
       
	public boolean isOutsideBounds(){
		return false;
	}
	
	public Rect getMe(){
		return new Rect((int) x, (int) y, (int) x + dstwidth, (int) y + dstheight);
	}
 
	public void onDraw(Canvas canvas) {
		if((this.x + this.dstwidth) - GameView.xScroll >= 0 && this.x - GameView.xScroll <= GameView.width && (this.y + this.dstheight) - GameView.yScroll >= 0 && this.y - GameView.yScroll <= GameView.height){
			update();
			int srcX = currentFrame * width;
			int srcY = aniRow * height;
			Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
			Rect dst = new Rect((int) x - (int) GameView.xScroll, (int) y - (int) GameView.yScroll, (int) x + dstwidth - (int) GameView.xScroll, (int) y + dstheight - (int) GameView.yScroll);
			canvas.drawBitmap(bmp, src, dst, null);
		}
		
	}	
 
	private int getAnimationRow() {
		double dirDouble = (Math.atan2(xSpeed, ySpeed) / (Math.PI / 2) + 2);
		int direction = (int) Math.round(dirDouble) % rows;
		return DIRECTION_TO_ANIMATION_MAP[direction];
	}
 
	public boolean isCollition(float x2, float y2) {
		return x2 > x && x2 < x + dstwidth && y2 > y && y2 < y + dstheight;
	}
}